import { Image, Layout, Menu, MenuProps } from "antd";

import useSetting from "@/hook/useSetting";
import styles from "./index.module.less";
import { getRoutes } from "@/router";
import { useEffect, useRef, useState } from "react";
import logo from "@/assets/react.svg";
import { useLocation, useNavigate } from "react-router-dom";
import { getStorage } from "@/utils/utils";
import { TOKEN_NAME } from "@/config";
const { Sider } = Layout;
type MenuItem = Required<MenuProps>["items"][number];
function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[]
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem;
}
const Slider: React.FC<{ collapsed: boolean }> = (props) => {
  const { collapsed } = props;
  const navigate = useNavigate();
  const location = useLocation();

  const { title } = useSetting();
  const routeArr = getRoutes();
  const menus: any = (data: any[]) => {
    return data.map((item: any) => {
      return getItem(
        item.meta.name,
        item.path,
        item.meta.icon,
        item.children && menus(item.children)
      );
    });
  };
  const [curKey, setCurKey] = useState([""]);
  const [openKey, setOpenKey] = useState<any[]>();

  const items: MenuItem[] = menus(routeArr);
  const getOpenKeys = (path: string) => {
    let openKey = [];
    openKey = path.split("/").map((item) => "/" + item);
    setOpenKey(openKey);
  };
  //重定向路由
  const rediretRoute = () => {
    routeArr.forEach((ite) => {
      if (ite.path == location.pathname && ite.redirect) {
        navigate(ite.children[0].path, { replace: true });
      }
    });
  };

  // 监听路由
  useEffect(() => {
    setCurKey([location.pathname]);
    rediretRoute();
    getOpenKeys(location.pathname);
  }, [location]);

  // 路由点击事件
  const clickMenus = (props: any) => {
    navigate(props.key);
  };

  const handleChange = (openKeys: string[]) => {
    setOpenKey(openKeys);
  };

  return (
    <Sider
      className={styles.slide}
      trigger={null}
      collapsible
      collapsed={collapsed}
    >
      <div
        style={{
          height: "64px",
          fontSize: "18px",
          lineHeight: "64px",
          fontWeight: "700",
          backgroundColor: "#fff",

          whiteSpace: "nowrap",
          textAlign: "center",
        }}
      >
        <Image src={logo} preview={false} />
        {!collapsed ? (
          <span style={{ whiteSpace: "nowrap" }}> {title}</span>
        ) : null}
      </div>
      <Menu
        theme="light"
        onClick={clickMenus}
        onOpenChange={handleChange}
        selectedKeys={curKey}
        openKeys={openKey}
        mode="inline"
        items={items}
      />
    </Sider>
  );
};

export default Slider;
